<template>
    <div class="container">
        <el-tabs tab-position="left" style="height: 1000px;width: 150%;" class="demo-tabs">
            <el-tab-pane label="最近报名表">
                <el-form ref="formRef" :rules="rules" :model="applicationForm" label-width="120px"
                    label-position="left">
                    <el-row :gutter="50">
                        <el-col :span="10">
                            <el-form-item label="报考驾照类型" prop="licence">
                                <el-select v-model="applicationForm.licence" placeholder="Select">
                                    <el-option v-for="item in licenceOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="身份证" prop="student.studentIdentityId">
                                <el-input v-model="applicationForm.student.studentIdentityId"></el-input>
                            </el-form-item>
                            <el-form-item label="姓名" prop="student.studentName">
                                <el-input v-model="applicationForm.student.studentName"></el-input>
                            </el-form-item>
                            <el-form-item label="年龄" prop="student.studentAge">
                                <el-input-number v-model="applicationForm.student.studentAge" :min="18" :max="100" />
                            </el-form-item>
                            <el-form-item label="性别" prop="student.studentSex">
                                <el-select v-model="applicationForm.student.studentSex" placeholder="请选择">
                                    <el-option key="男" label="男" value="男"></el-option>
                                    <el-option key="女" label="女" value="女"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="电话号码" prop="student.studentPhone">
                                <el-input v-model="applicationForm.student.studentPhone"></el-input>
                            </el-form-item>
                            <el-form-item v-show="newApplication" label="体检表" prop="student.studentPhone">
                                <div class="col-span-4 flex items-center h-10 px-2 border border-slate-300">
                                    <input class="text-xs" type="file" id="fileInput" name="fileInput"
                                        accept=".pdf, .doc, .docx" multiple ref="fileInput" />
                                </div>
                            </el-form-item>
                            <el-form-item v-show="!newApplication" label="体检表" prop="coach">
                                <el-button @click="downloadFile(applicationForm.applicationId)">下载并查看</el-button>
                            </el-form-item>
                            <el-form-item v-show="newApplication" label="请选择教练" prop="coach">
                                <el-select placeholder="请选择" @click="coachVisible = true">
                                </el-select>
                            </el-form-item>
                            <el-form-item label="--教练信息">
                                <el-card v-if="applicationForm.coach">
                                    <el-form :label-position="left" label-width="auto" :model="formLabelAlign"
                                        style="max-width: 600px">
                                        <el-form-item label="教练姓名：">
                                            <el-input v-model="applicationForm.coach.coachName" readonly />
                                        </el-form-item>
                                        <el-form-item label="教练年龄：">
                                            <el-input v-model="applicationForm.coach.coachAge" readonly />
                                        </el-form-item>
                                        <el-form-item label="教练性别：">
                                            <el-input v-model="applicationForm.coach.coachSex" readonly />
                                        </el-form-item>
                                        <el-form-item label="联系方式：">
                                            <el-input v-model="applicationForm.coach.coachPhone" readonly />
                                        </el-form-item>
                                        <el-form-item label="练习车辆：">
                                            <el-input v-model="applicationForm.coach.coachCar" readonly />
                                        </el-form-item>
                                    </el-form>
                                </el-card>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item v-show="newApplication">
                                <el-button type="primary" @click="onSubmit(formRef)">表单提交</el-button>
                                <el-button @click="onReset(formRef)">重置表单</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form></el-tab-pane>
            <el-tab-pane label="所有报名表">
                <el-collapse accordion>
                    <el-collapse-item v-for="(application, index) in applications" :key="index"
                        :title="'报名表 ' + (index + 1)">
                        <div>
                            <el-card style="max-width: 600px;">
                                <p><strong>报考驾照类型:</strong> {{ application.licence.licenceType }}</p>
                                <p><strong>报考时间:</strong> {{ application.applicationTime }}</p>
                                <p><strong>身份证:</strong> {{ application.student.studentIdentityId }}</p>
                                <p><strong>姓名:</strong> {{ application.student.studentName }}</p>
                                <p><strong>年龄:</strong> {{ application.student.studentAge }}</p>
                                <p><strong>性别:</strong> {{ application.student.studentSex }}</p>
                                <p><strong>电话号码:</strong> {{ application.student.studentPhone }}</p>
                                <p><strong>状态:</strong> {{ application.applicationFinished }}</p>
                                <el-button size="small" @click="downloadFile(application.applicationId)">查看报名表</el-button>
                            </el-card>
                            <br>
                            <el-form-item>
                                <el-card>
                                    <el-form :label-position="left" label-width="auto" :model="formLabelAlign"
                                        style="max-width: 600px">
                                        <h4>教练信息</h4>
                                        <el-form-item label="教练姓名：">
                                            <el-input v-model="application.coach.coachName" readonly />
                                        </el-form-item>
                                        <el-form-item label="教练年龄：">
                                            <el-input v-model="application.coach.coachAge" readonly />
                                        </el-form-item>
                                        <el-form-item label="教练性别：">
                                            <el-input v-model="application.coach.coachSex" readonly />
                                        </el-form-item>
                                        <el-form-item label="联系方式：">
                                            <el-input v-model="application.coach.coachPhone" readonly />
                                        </el-form-item>
                                        <el-form-item label="练习车辆：">
                                            <el-input v-model="application.coach.coachCar" readonly />
                                        </el-form-item>
                                    </el-form>
                                </el-card>
                            </el-form-item>
                        </div>
                    </el-collapse-item>
                </el-collapse>
            </el-tab-pane>
        </el-tabs>
        <el-dialog v-model="coachVisible" width="600">
            <template #header="{ titleId, titleClass }">
                <div class="my-header">
                    <h4 :id="titleId" :class="titleClass">设置偏好，系统将会为您推荐教练</h4>
                </div>
            </template>
            <el-form-item label="教练性别">
                <el-select v-model="coachPreference.sex" placeholder="请选择教练性别">
                    <el-option key="无要求" label="无要求" value="null"></el-option>
                    <el-option key="男" label="男" value="男"></el-option>
                    <el-option key="女" label="女" value="女"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="教练年龄">
                <el-form-item>
                    <el-input-number v-model="coachPreference.age1" :min="18" :max="80" />
                    <el-icon>
                        <SemiSelect />
                    </el-icon><el-icon>
                        <ArrowRightBold />
                    </el-icon>
                    <el-input-number v-model="coachPreference.age2" :min="18" :max="80" />
                </el-form-item>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Check" @click="recommend()">确定</el-button>
                <el-button icon="Refresh" @click="reset()">重置</el-button>
            </el-form-item>
            <h4 v-show="showCoachList">以下是为您推荐的教练：</h4>
            <el-table v-show="showCoachList" :data="filteredCoach">
                <el-table-column property="coachName" label="姓名" width="150" />
                <el-table-column property="coachSex" label="性别" width="200" />
                <el-table-column property="coachAge" label="年龄" />
                <el-table-column type="action" label="操作" width="270">
                    <template v-slot="{ row }">
                        <el-button type="primary" size="mini" @click="chooseCoach(row)">
                            选择
                        </el-button>

                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="forms">
import { onMounted, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormProps, FormRules } from 'element-plus';

import type { coachItemData } from '@/api/coach';
import * as coachApi from '@/api/coach';
import type { applicationItemData } from '@/api/application';
import * as applicationApi from '@/api/application';
import { studentItemData } from '@/api/student';
import * as licenceApi from '@/api/licence';
import { licenceItemData } from '@/api/licence';
import * as medicalApi from '@/api/medical';

import axios from 'axios';
const uploadFiles = (applicationId) => {
    const inputElement = document.getElementById('fileInput') as HTMLInputElement;

    // 确保 input 元素存在并且是 HTMLInputElement 类型
    if (inputElement && inputElement.files) {
        const files = inputElement.files;
        const formData = new FormData();
        for (let i = 0; i < files.length; i++) {
            formData.append('files', files[i]);
        }
        formData.append('applicationId', applicationId); // 假设 applicationId 为 1

        // 发送请求
        axios.post('http://localhost:8080/medical/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
            .then(response => {
                // 处理上传成功后的逻辑
                console.log('上传成功', response.data);
            })
            .catch(error => {
                // 处理上传失败后的逻辑
                console.error('上传失败', error);
            });
    } else {
        console.error('无法获取文件输入元素或文件列表');
    }
}
const downloadFile = (applicationId) => {
    axios.get(`http://localhost:8080/medical/getUrl/${applicationId}`, { responseType: 'blob' })
        .then(response => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', studentForm.value.studentName+"体检表.pdf"); // 可以根据需要动态设置文件名
            document.body.appendChild(link);
            link.click();
            link.remove();
        })
        .catch(error => {
            console.error('下载失败', error);
        });
}
const coachVisible = ref(false)
const showCoachList = ref(false)
const newApplication = ref(false)
const filteredCoach = ref<coachItemData[]>([]);
const coachPreference = ref({ sex: 'null', age1: 23, age2: 80 });
const licenceOptions = ref<Array<{ value: string; label: string }>>([
    { value: '', label: '加载中...' }
]);

const labelPosition = ref<FormProps['labelPosition']>('right')
const rules: FormRules = {
    "student.studentPhone": [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
    "student.studentSex": [{ required: true, message: '请选择性别', trigger: 'blur' }],
    'student.studentAge': [{ required: true, message: '请输入年龄', trigger: 'blur' }],
    "student.studentName": [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    "student.studentIdentityId": [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
    licence: [{ required: true, message: '请选择驾照类型', trigger: 'blur' }],
    coach: [{ required: true, message: '请选择教练', trigger: 'blur' }],
};
const formRef = ref<FormInstance>();
// 定义初始的空对象
const initialStudentData: studentItemData = {
    studentId: 0,
    studentName: '',
    studentIdentityId: '',
    studentSex: '男',
    studentAge: 18,
    studentPhone: ''
};
// 初始化 studentForm 为初始的空对象
const studentForm = ref<studentItemData>({ ...initialStudentData });
// 获取并解析 localStorage 中的 studentInfo
const storedStudentInfo = localStorage.getItem("studentInfo");
if (storedStudentInfo) {
    try {
        studentForm.value = JSON.parse(storedStudentInfo) as studentItemData;
    } catch (e) {
        console.error("Failed to parse studentInfo from localStorage", e);
    }
}
const applicationForm = ref<applicationItemData>({
    applicationId: 0,
    applicationTime: null,
    applicationPreference: '',
    applicationFinished: '',
    progressId: 0,
    coachId: 0,
    studentId: 0,
    licenceId: 0,
    progress: null,
    coach: null,
    student: studentForm.value,
    licence: null
});

const generateData = () => {
    const data = []
    for (let i = 1; i <= 15; i++) {
        data.push({
            key: i,
            label: `Option ${i}`,
            disabled: i % 4 === 0,
        })
    }
    return data
}

const transferData = ref(generateData())
// 提交
const setApplicationTimeToCurrentDate = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0'); // Months are zero-based
    const day = now.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
};
const onSubmit = (formEl: FormInstance | undefined) => {
    // 表单校验
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            applicationForm.value.coachId = applicationForm.value.coach.coachId;
            applicationForm.value.studentId = applicationForm.value.student.studentId;
            applicationForm.value.licenceId = applicationForm.value.licence;
            applicationForm.value.applicationTime = setApplicationTimeToCurrentDate();
            delete applicationForm.value.licence;
            delete applicationForm.value.coach;
            delete applicationForm.value.progress;
            applicationForm.value.applicationFinished = '待审核';
            // delete applicationForm.value.student;
            console.log(applicationForm.value);
            applicationApi.addApplication(applicationForm.value, studentForm.value.studentId).then((resp) => {
                if (resp.data.data.addApplication.applicationId != null) {
                    uploadFiles(resp.data.data.addApplication.applicationId);
                }
                ElMessage.success('报名表提交成功！');
                initAll();
            }).catch((resp) => {
                ElMessage.warning('报名表提交失败！');
                console.log(resp)
            })
        } else {
            return false;
        }
    });
};
// 重置
const onReset = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};
const recommend = async () => {
    const response = await coachApi.getCoachBySexOrAge(coachPreference.value.sex, coachPreference.value.age1, coachPreference.value.age2);
    console.log(coachPreference.value);
    console.log(response.data.data.getCoachBySexOrAge);
    filteredCoach.value = response.data.data.getCoachBySexOrAge;
    showCoachList.value = true;
}
const reset = () => {
    coachPreference.value.sex = 'null';
    coachPreference.value.age1 = 21;
    coachPreference.value.age2 = 80;
    showCoachList.value = false;
}
const chooseCoach = (row) => {
    applicationForm.value.coach = row;
    console.log(applicationForm);
    reset();
    coachVisible.value = false;
}
const initLicenceOption = async () => {
    try {
        const resp = await licenceApi.fetchData();
        licenceOptions.value = resp.data.licences.map((element: any) => ({
            value: element.licenceId,
            label: element.licenceType
        }));
    } catch (error) {
        console.error(error);
    }
};

const initApplication = async () => {
    try {
        const resp = await applicationApi.getApplicationByStudentId(studentForm.value.studentId);
        if (resp.data.data.getAllApplication.applicationId != null) {
            applicationForm.value = resp.data.data.getAllApplication;
            newApplication.value = false;
        } else {
            newApplication.value = true;
        }
        console.log(resp);
    } catch (error) {
        console.error(error);
    }
}
const applications = ref();
const initApplications = async () => {
    try {
        const resp = await applicationApi.getStudentApplication(studentForm.value.studentId);
        applications.value = resp.data.data.getApplication;
        console.log(applications.value);
    } catch (error) {
        console.error(error);
    }
}
const initAll = () => {
    initLicenceOption();
    initApplication();
    initApplications();
};
onMounted(() => {
    initAll();
});

</script>